package com.ruoyi.lab.aop;

import com.ruoyi.lab.domain.LabMessage;
import com.ruoyi.lab.domain.LabOperateMessage;
import com.ruoyi.lab.service.ILabMessageService;
import com.ruoyi.lab.service.ILabOperateMessageService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 自定义切面，记录实验室操作日志
 */
@Aspect
@Component
public class LabAspect {

    @Autowired
    private ILabMessageService labMessageService;
    @Autowired
    private ILabOperateMessageService labOperateMessageService;

    @Pointcut("@annotation(com.ruoyi.lab.annotation.LabOperate)")
    public void pointcut() {}

    @Around("pointcut()")
    @Transactional(rollbackFor = Exception.class)
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        LabOperateMessage labOperateMessage = new LabOperateMessage();
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            // 此处解析的都是跟实验室提交、审批有关的操作，传递的参数都是id
            if (arg instanceof Long) {
                Long labId = (Long) arg;
                LabMessage labMessage = labMessageService.selectLabMessageByLabId(labId);
                labOperateMessage.setLabId(labId);
                labOperateMessage.setBeforeStatus(labMessage.getLabStatus());
            }
        }

        Object result = joinPoint.proceed();

        for (Object arg : args) {
            // 此处解析的都是跟实验室提交、审批有关的操作，传递的参数都是id
            if (arg instanceof Long) {
                Long labId = (Long) arg;
                LabMessage labMessage = labMessageService.selectLabMessageByLabId(labId);
                if (labOperateMessage.getBeforeStatus().equals(labMessage.getLabStatus())) {
                    // 如果操作前后的状态一致，表示可能因各种原因未操作成功，不记录
                    return result;
                }

                labOperateMessage.setAfterStatus(labMessage.getLabStatus());
            }
        }

        labOperateMessageService.insertLabOperateMessage(labOperateMessage);
        return result;
    }
}
